package com.fanw.easyExport.core.file;

import com.fanw.easyExport.core.config.ExportConfig;
import com.fanw.easyExport.core.config.FieldConfig;
import com.fanw.easyExport.core.model.ExportResult;

import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;

/**
 * 文件生成器
 */
public class FileGenerator {

    public ExportResult generateFile(ExportConfig config, List<Map<String, Object>> data) {
        Path filePath = Paths.get(config.getOutputPath());
        ExportResult result = new ExportResult();
        result.setTaskName(config.getTaskName());

        try (BufferedWriter writer = Files.newBufferedWriter(filePath)) {
            // 写入表头
            if (config.isIncludeHeader()) {
                writeHeader(writer, config);
            }

            // 写入数据行
            int rowCount = 0;
            for (Map<String, Object> row : data) {
                writeRow(writer, config, row);
                rowCount++;
            }

            result.setSuccess(true);
            result.setOutputPath(filePath.toString());
            result.setRowCount(rowCount);
            result.setMessage("数据导出成功");

        } catch (IOException e) {
            result.setSuccess(false);
            result.setMessage("数据导出失败: " + e.getMessage());
        }

        return result;
    }

    private void writeHeader(BufferedWriter writer, ExportConfig config) throws IOException {
        StringBuilder headerLine = new StringBuilder();
        for (FieldConfig field : config.getFields()) {
            if (headerLine.length() > 0) {
                headerLine.append(config.getDelimiter());
            }
            headerLine.append(field.getTargetField());
        }
        writer.write(headerLine.toString());
        writer.write(config.getLineSeparator());
    }

    private void writeRow(BufferedWriter writer, ExportConfig config, Map<String, Object> row) throws IOException {
        StringBuilder dataLine = new StringBuilder();
        for (FieldConfig field : config.getFields()) {
            if (dataLine.length() > 0) {
                dataLine.append(config.getDelimiter());
            }

            Object value = row.get(field.getSourceField());
            if (value == null) {
                value = field.getDefaultValue() != null ? field.getDefaultValue() : "";
            }

            // 简单处理：转义字段中的分隔符和换行符
            String stringValue = value.toString()
                    .replace(config.getDelimiter(), "\\" + config.getDelimiter())
                    .replace("\n", "\\n")
                    .replace("\r", "\\r");

            dataLine.append(stringValue);
        }
        writer.write(dataLine.toString());
        writer.write(config.getLineSeparator());
    }
}
